package com.gitee.huanminabc.utils_tools.config_refresh.file;
import com.gitee.huanminabc.jcommon.file.FileUtil;
import com.gitee.huanminabc.jcommon.test.PathUtil;
import com.gitee.huanminabc.utils_tools.config_refresh.utils.YamlToPropertiesConverter;
import com.gitee.huanminabc.utils_tools.config_refresh.enums.ConfigFileTypeEnum;
import com.gitee.huanminabc.utils_tools.spring_base.utils.SpringContextUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.Properties;

@Component
public class YmlFileRead implements ConfigFileRead {

    @Override
    public ConfigFileTypeEnum fileType() {
        return ConfigFileTypeEnum.YML;
    }

    public Properties read() {
        Properties properties = readPeer();
        properties.putAll(readConfig());
        return properties;
    }

    //获取项目外部配置文件 同级目录下的配置文件
    public Properties readPeer() {
        String home =  PathUtil.getCurrentProjectAbsolutePath();
        List<String> files = FileUtil.getFiles(home);
        Properties properties = new Properties();
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        if (applicationContext == null) {
            return properties;
        }
        for (String file : files) {
            if (file.endsWith(".yml") || file.endsWith(".yaml")) {
                Properties newProperties = YamlToPropertiesConverter.convertYamlToPropertiesSpring(new File(file), applicationContext);
                properties.putAll(newProperties);

            }
        }
        return properties;
    }
    //获取项目同级config目录下的配置文件
    public Properties readConfig() {

        String home = PathUtil.getCurrentProjectAbsolutePath() + File.separator+ "config";
        List<String> files = FileUtil.getFiles(home);
        Properties properties = new Properties();
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        if (applicationContext == null) {
            return properties;
        }
        for (String file : files) {
            if (file.endsWith(".yml") || file.endsWith(".yaml")) {
                Properties newProperties = YamlToPropertiesConverter.convertYamlToPropertiesSpring(new File(file),applicationContext);
                properties.putAll(newProperties);

            }
        }
        return properties;
    }



}
